import 'dart:async';
import 'dart:convert';

import 'package:bot_toast/bot_toast.dart';
import 'package:dio/dio.dart';
import 'package:exams_app/home_module/exams_module/view.dart';
import 'package:exams_app/login_module/real_name_authen/view.dart';
import 'package:exams_app/net/Address.dart';
import 'package:exams_app/net/DioManager.dart';
import 'package:exams_app/net/persisten_storage.dart';
import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:get/get_state_manager/src/simple/get_controllers.dart';

// import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
// import 'package:get/get.dart';

class HomeModuleLogic extends GetxController {

  Rx<ExamsModel> model;

  RxMap appHomeJson;

  RxMap refJson;

  RxMap apidoneJson;

  RxMap apinoexam;

  final haveExams = true.obs;
  final haveLive = true.obs;
  
  final stateKS = ''.obs;


  final daoshiji = 0.obs;


  var okexams = ''.obs;

  var noexams = ''.obs;


  List dataList = List();


  /// 违规图片上传

  void requestDataWithWeiGuiPic(var imageBase64,var order_id)async{

    var params = {
      'form-field-binary-image':imageBase64,
      'form-field-integer-order_id':order_id,
      'form-field-char-name':'违规',
      'form-field-integer-angle':'77'
    };
    String result = await DioUtils(url:await PersistentStorage().getStorage('urlStr') ).postModel(Address.getattt,model: 'res.face.angle',
      function_name: '_api_write_image',params: params);

  }


  /// 提交答案

  void requestDataWithTiJiao(var answer,bool is_ok,var id)async{


    String result = await DioUtils(
        url: await PersistentStorage().getStorage('urlStr'))
        .postModel(
        '/api/v1/write/${id}',
        model: 'res.exam.line',
        params: {'form-field-char-answer': answer,'form-field-boolean-is_ok':is_ok});
    Map json = jsonDecode(result);



    // requestDataWithExams('15');
    requestDataWithExams('${appHomeJson['data']['exam_id']}');
  }

  /// 人脸识别

  Future requestDataWithAIface(var ai_face)async{
    String result =
    await DioUtils(url: await PersistentStorage().getStorage('urlStr'))
        .postModel('${Address.getattt}}',
        model: 'res.partner',
        function_name: '_api_ai_face',
        params: {'ai_face': '${ai_face}'});

    Map json = jsonDecode(result);
    // BotToast.showText(text: '${json['message']}');
    return json;
  }

  /// 人脸角度 上传
  Future requestDataWithAIfaceJiaodu(var ai_face)async{

    print('   ================ 开始上传图片');
    print('图片地址 ============== ${ai_face}');

    // var params = {
    //   'image':ai_face,
    //   'user_id':2,
    //   'user_name':'admin'
    // };
    var formData = FormData.fromMap({
      "user_name": "${await PersistentStorage().getStorage('name')}",
      "user_id": '${await PersistentStorage().getStorage('uid')}',
      "image": await MultipartFile.fromFile(ai_face,filename: "image.jpg"),
    });
    print(' 上传参数类型=========================== ${formData.files}');

    Response response =  await Dio().post('http://36.153.159.19:8088/index',data:formData);
    // String result =  await DioUtils(url: 'http://36.153.159.19:8088/index').post('',data:params);
    print('返回 ====================== post result ---${response.data}');

    var json = response.data;

    // BotToast.showText(text: '${json['message']}');
    return json;
  }


  /// 获取rtmp推流

 Future getrtmpUrlRequestData()async{

    String result =
    await DioUtils(url: await PersistentStorage().getStorage('urlStr'))
        .postModel(Address.getattt,
        model: 'res.exam',
        function_name: '_api_get_rtmpURl',);

    Map json = jsonDecode(result);

    return json;
  }

  /// 考试
  void requestDataWithExams(var exam_id) async {
    String result =
        await DioUtils(url: await PersistentStorage().getStorage('urlStr'))
            .postModel(Address.getattt,
                model: 'res.exam',
                function_name: '_api_one',
                params: {'exam_id': '${exam_id}'});

    Map json = jsonDecode(result);

    if(json['errmsg'] == 'no'){

      // Toast.toast(Get.overlayContext,msg: json['message']);
      // Get.off(HomeModulePage());
      BotToast.showText(text: json['message']);

    }

    // if(json['errmsg']=='no'){
    //   Get.off(HomeModulePage());
    //   return;
    // }

    model = ExamsModel.fromJson(json).obs;


    for(int i =0;i<model.value.data[0].questionIds.length;i++){
      
      if(model.value.data[0].questionIds[i].method=='多选题'){
        for(int j = 0;j<model.value.data[0].questionIds[i].questionLines.length;j++){

          print(model.value.data[0].questionIds[i].questionLines[j].aZ);
          if(model.value.data[0].questionIds[i].answer!=false){
            List c = model.value.data[0].questionIds[i].answer.split(',');
            for(int k =0;k<c.length;k++){
              if(c[k]==model.value.data[0].questionIds[i].questionLines[j].aZ){
                model.value.data[0].questionIds[i].questionLines[j].isSelect = true;
              }
            }
          }
        }
      }

      ///单选

      else {
        for (int j = 0; j <
            model.value.data[0].questionIds[i].questionLines.length; j++) {
          if (model.value.data[0].questionIds[i].answer != false) {
            if (model.value.data[0].questionIds[i].questionLines[j].aZ.contains(
                model.value.data[0].questionIds[i].answer)) {
              model.value.data[0].questionIds[i].questionLines[j].isSelect = true;
            }else{
              model.value.data[0].questionIds[i].questionLines[j].isSelect = false;
            }
          }
        }
      }

    }

    // print(model.value.message);

    update();
  }



  /// 考试须知
    void requestDataWithApiRef()async{

        var  params = {
          'ref_id':'exam.exam_description_all',
        };

        String result = await DioUtils(url: await PersistentStorage().getStorage('urlStr')).
        postModel(Address.getattt,function_name:'_api_ref',model:'res.users',params:params );

        Map json  = jsonDecode(result);

        refJson = json.obs;

        update();

  }


  /// 未做的题目
   Future requestDataWith_api_no_exam(var exam_id)async{

    var  params = {
      'exam_id':'${exam_id}',
    };

    String result = await DioUtils(url: await PersistentStorage().getStorage('urlStr')).
    postModel(Address.getattt,function_name:'_api_no_exam',model:'res.exam',params:params);
    Map json = jsonDecode(result);

    apinoexam = json.obs;
    //
    update();

    return apinoexam;
  }

  /// APP首页
  void requestDataWithXuzhi() async {
    String result =
        await DioUtils(url: await PersistentStorage().getStorage('urlStr'))
            .postModel(Address.getattt,
                model: 'res.users', function_name: '_api_main');

    Map json = jsonDecode(result);

    appHomeJson = json.obs;
    


    if (appHomeJson['data']['exam_id']=='') {
      haveExams.value = false;
    } else {
      haveExams.value = true;
    }

    if (appHomeJson['data']['live_id']=='') {
      haveLive.value = false;
    } else {
      haveLive.value = true;
    }
    
    if(appHomeJson['data']['exam_seconds']<=0&&appHomeJson['data']['exam_seconds']>-600){
      stateKS.value = '考试已经开始,请尽快开始考试';
      daoshiji.value = 0;
    }else if(appHomeJson['data']['exam_seconds']>0){
      stateKS.value = '考试倒计时';
      daoshiji.value = 0;
      daoshiji.value = appHomeJson['data']['exam_seconds'];
    }else if(appHomeJson['data']['exam_seconds']<-600){
      stateKS.value = '考试已超过10分钟,无法考试';
      daoshiji.value = 0;
    }




    update();
  }

  Timer _timer;

  void startTimer() {
    //设置 1 秒回调一次
    const period = const Duration(seconds: 1);
    _timer = Timer.periodic(period, (timer) {
      //更新界面

        //秒数减一，因为一秒回调一次
        daoshiji.value--;
//        print('我在更新界面>>>>>>>>>>>>>> $seconds');
//         countContent = constructTime(seconds);

      if ( daoshiji.value == 0) {
        //倒计时秒数为0，取消定时器

        requestDataWithXuzhi();


        print('我被取消了  ');
        BotToast.showText(text: '考试时间到');
        // cancelTimer();
        // Get.off(ExamsCompletePage());
        // getData();
      }
    });
  }

  void cancelTimer() {
    if (_timer != null) {
      _timer.cancel();
      _timer = null;
    }
  }





  /// 交卷 接口
  void requestDataWithCommitExams(var exam_id) async {

    BotToast.showLoading(clickClose: true);

    String result =
    await DioUtils(url: await PersistentStorage().getStorage('urlStr'))
        .postModel(Address.getattt,
        model: 'res.exam', function_name: '_api_done',params: {'exam_id':exam_id});

    Map json = jsonDecode(result);

    apidoneJson = json.obs;

    BotToast.closeAllLoading();

    update();
  }



  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();

    requestDataWithXuzhi();
    // requestDataWithUserInfo();
    // requestDataWithUser();
    requestDataWithApiRef();
  }
  @override
  void onReady() {
    // TODO: implement onInit
    super.onReady();

  }
}

class ExamsModel {
  var errcode;
  var errmsg;
  List<Data> data;
  var message;

  ExamsModel({this.errcode, this.errmsg, this.data, this.message});

  ExamsModel.fromJson(Map<String, dynamic> json) {
    errcode = json['errcode'];
    errmsg = json['errmsg'];
    if (json['data'] != null) {
      data = new List<Data>();
      json['data'].forEach((v) {
        data.add(new Data.fromJson(v));
      });
    }
    message = json['message'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['errcode'] = this.errcode;
    data['errmsg'] = this.errmsg;
    if (this.data != null) {
      data['data'] = this.data.map((v) => v.toJson()).toList();
    }
    data['message'] = this.message;
    return data;
  }
}

class Data {
  int  leave;
  var image128;
  var pastTime;
  var createDate;
  var id;
  var name;
  var textName;
  var dateOrder;
  var dateStart;
  var dateEnd;
  var planIdName;
  var state;
  var scores;
  var error;
  var right;
  var type;
  int  seconds;
  int  end_seconds;
  List<QuestionIds> questionIds;
  var questionCount;

  Data(
      {this.image128,
         this.leave,
      this.pastTime,
      this.createDate,
      this.id,
      this.name,
      this.textName,
      this.dateOrder,
      this.dateStart,
      this.dateEnd,
      this.planIdName,
      this.state,
      this.scores,
      this.error,
      this.right,
      this.type,
      this.questionIds,
        this.seconds,
        this.end_seconds,
      this.questionCount});

  Data.fromJson(Map<String, dynamic> json) {
    leave = json['leave'];
    image128 = json['image_128'];
    pastTime = json['past_time'];
    createDate = json['create_date'];
    id = json['id'];
    name = json['name'];
    textName = json['text_name'];
    dateOrder = json['date_order'];
    dateStart = json['date_start'];
    dateEnd = json['date_end'];
    planIdName = json['plan_id_name'];
    state = json['state'];
    scores = json['scores'];
    error = json['error'];
    right = json['right'];
    type = json['type'];
    seconds = json['seconds'];
    end_seconds = json['end_seconds'];
    if (json['question_ids'] != null) {
      questionIds = new List<QuestionIds>();
      json['question_ids'].forEach((v) {
        questionIds.add(new QuestionIds.fromJson(v));
      });
    }
    questionCount = json['question_count'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['image_128'] = this.image128;
    data['past_time'] = this.pastTime;
    data['create_date'] = this.createDate;
    data['id'] = this.id;
    data['name'] = this.name;
    data['text_name'] = this.textName;
    data['date_order'] = this.dateOrder;
    data['date_start'] = this.dateStart;
    data['date_end'] = this.dateEnd;
    data['plan_id_name'] = this.planIdName;
    data['state'] = this.state;
    data['scores'] = this.scores;
    data['error'] = this.error;
    data['right'] = this.right;
    data['type'] = this.type;
    if (this.questionIds != null) {
      data['question_ids'] = this.questionIds.map((v) => v.toJson()).toList();
    }
    data['question_count'] = this.questionCount;
    return data;
  }
}

class QuestionIds {
  var id;
  var answer;
  var isOk;
  var method;
  var name;

  List<QuestionLines> questionLines;
  List<int> questionIds;

  QuestionIds(
      {this.id,
      this.answer,
      this.isOk,
      this.questionLines,
      this.questionIds,
        this.method,
      this.name});

  QuestionIds.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    answer = json['answer'];
    isOk = json['is_ok'];
    name = json['name'];
    method = json['method'];
    if (json['question_lines'] != null) {
      questionLines = new List<QuestionLines>();
      json['question_lines'].forEach((v) {
        questionLines.add(new QuestionLines.fromJson(v));
      });
    }
    questionIds = json['question_ids'].cast<int>();
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['answer'] = this.answer;
    data['is_ok'] = this.isOk;
    if (this.questionLines != null) {
      data['question_lines'] =
          this.questionLines.map((v) => v.toJson()).toList();
    }
    data['question_ids'] = this.questionIds;
    return data;
  }
}

class QuestionLines {
  var id;
  String aZ;
  var name;
  var reply;
  var isSelect = false;

  QuestionLines({this.id, this.aZ, this.name, this.reply});

  QuestionLines.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    aZ = json['a_z'];
    name = json['name'];
    reply = json['reply'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['a_z'] = this.aZ;
    data['name'] = this.name;
    data['reply'] = this.reply;
    return data;
  }
}



